package com.epfresh.views.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.R;
import com.epfresh.adapter.MsgTagAdapter;
import com.epfresh.bean.CartGood;
import com.epfresh.bean.MsgTag;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * @author wangzhanghuan
 * @version 1.0
 * @date create 2017/11/13
 * @Description
 */
public class MsgDialog extends Dialog {

    public interface OnCommitListener {
        void onCommit(String msg, String goodsId);
    }

    private TextView tvSure;
    private EditText etContent;
    private ImageView ivEtClean;
    private RecyclerView mRvTag;

    private OnCommitListener onCommitListener;
    private MsgTagAdapter mMsgTagAdapter;
    private List<MsgTag> msgTagList = new ArrayList<>();

    private String mGoodsId;
    boolean keyBoardShown;

    public OnCommitListener getOnCommitListener() {
        return onCommitListener;
    }

    public void setOnCommitListener(OnCommitListener onCommitListener) {
        this.onCommitListener = onCommitListener;
    }

    public MsgDialog(@NonNull Context context) {
        super(context, R.style.Dialog);

    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.dialog_msg);
        //按空白处不能取消动画
        setCanceledOnTouchOutside(true);
        Window dialogWindow = getWindow();
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = LocalDisplay.SCREEN_WIDTH_PIXELS;
        dialogWindow.setAttributes(lp);
        initView();

    }
    int [] location = {0,0};


    private void initView() {

        tvSure = (TextView) findViewById(R.id.tv_sure);
        etContent = (EditText) findViewById(R.id.et_content);

        mRvTag = (RecyclerView) findViewById(R.id.rv_tag);

        ivEtClean = (ImageView) findViewById(R.id.iv_et_clean);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvTag.setLayoutManager(layoutManager);

        mMsgTagAdapter = new MsgTagAdapter(msgTagList);
        mRvTag.setAdapter(mMsgTagAdapter);
        mMsgTagAdapter.setOnMsgTagSelectListener(new MsgTagAdapter.OnMsgTagSelectListener() {
            @Override
            public void onMsgTagSelect(boolean isSelect, MsgTag msgTag) {
                //etContent.setText(etContent.getText() + msgTag.getName());
                String s = etContent.getText().toString();
                if ("".equals(s.trim())) {
                    s = s + msgTag.getName();
                } else {
                    s = s + "，" + msgTag.getName();
                }
                etContent.setText(s);
                etContent.setSelection(etContent.length());
            }
        });
        etContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            //当键盘弹出隐藏的时候会 调用此方法。
            @Override
            public void onGlobalLayout() {
/*                Rect r = new Rect();
                //获取当前界面可视部分
                getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //获取屏幕的高度
                int screenHeight = getWindow().getDecorView().getRootView().getHeight();
                //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                int heightDifference = screenHeight - r.bottom;
                //无效
                if (heightDifference > 100){
                    //打开键盘
                    keyBoardShown = true;
                }else {// 软键盘收起的情况
                    if (keyBoardShown){
                        dismiss();

                    }
                    keyBoardShown = false;

                }*/
                int [] locationNow = {0,0};

                etContent.getLocationOnScreen(locationNow);
                if(location[1]==0){
                    location[1] = locationNow [1];
                }else {
                    if(location[1]>=locationNow[1]){
                        location[1] = locationNow[1];
                    }else {
                        dismiss();
                        return;
                    }
                }
/*                Log.e("__location0_____","______"+location[0]);
                Log.e("___location1____","______"+location[1]);
                Log.e("SCREEN_HEIGHT_PIXELS","______"+LocalDisplay.SCREEN_HEIGHT_PIXELS);
                Log.e("keyBoardShown","______"+keyBoardShown);

                if(location[1]<LocalDisplay.SCREEN_HEIGHT_PIXELS){
                    keyBoardShown = true;
                }
                if(keyBoardShown&&location[1]==LocalDisplay.SCREEN_HEIGHT_PIXELS) {
                    keyBoardShown = false;
                    Log.e("dismiss","______________________");
                    dismiss();
                    return;
                }*/
            }

        });
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    ivEtClean.setVisibility(View.VISIBLE);
                } else {
                    ivEtClean.setVisibility(View.GONE);
                }
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onCommitListener != null) {
                    onCommitListener.onCommit(etContent.getText().toString(), mGoodsId);
                }
            }
        });
        ivEtClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etContent.setText("");
            }
        });
    }
/*

    @Override
    public void dismiss() {
        super.dismiss();
    }
*/


    public void show(String goodsId,List<String> list,String msg) {
        this.mGoodsId = goodsId;
        if (goodsId != null) {
            show();
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    InputMethodManager inputManager =
                            (InputMethodManager) etContent.getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(etContent, 0);
                }
            }, 200);
        }
        msgTagList.clear();
        if(list!=null&&list.size()!=0){
            for(int i=0;i<list.size();i++) {
                MsgTag mt = new MsgTag();
                mt.setName(list.get(i));
                msgTagList.add(mt);
            }
        }
        mMsgTagAdapter.notifyDataSetChanged();
        etContent.setText(msg);
        if(msg!=null)
            etContent.setSelection(msg.length());
    }


    @Override
    //按键回调方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        //判断按键键值做出相应操作
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            dismiss();
            return true;
        }
        //其他按键继承系统属性
        return super.onKeyDown(keyCode, event);
    }


}
